# Before `make install' is performed this script should be runnable with
# `make test'. After `make install' it should work as `perl Proc-RPC.t'

#########################

# change 'tests => 1' to 'tests => last_test_to_print';

use Test::More;

BEGIN { use_ok('Proc::RPC') };
use Proc::RPC;


# Pruebas del método read_output_child
##########################################################################################################
{
	open my $f, '<', 't/ficherito.txt'; 
	local undef $/;
	my $ficherito = <$f>;
	close $f;
	
	is(Proc::RPC->read_child_output('t/ficherito.txt'), $ficherito, 'Testing the read_child_output method');	
}

# Basic test for join method
##########################################################################################################
{
	sub increment_array
	{
		my ($inc, @array) = @_;
		$_ += $inc for(@array);
		return @array;
	}
	
	my $inc = 34;
	my @a = (1,2,3,4,5,6,7);
	my @b = increment_array($inc, @a);
	
	my $proc = Proc::RPC->new();
	$proc->rpc(\&increment_array, ($inc, @a));
	my $r = $proc->join();

	# Join retorna un objeto Proc::RPC::Result	
	ok(ref $r eq 'Proc::RPC::Result', 'Expecting a Proc::RPC::Result object');
	
	my @result = @{$r->result()};	
	is_deeply(\@b,\@result, "Probando el join - Devolviendo listas"); 
}

# Join method returning sub routines
##########################################################################################################
{
	sub return_sub
	{
		return sub { 'Soy algo que devuelve una subrutina, devuelta por una subrutina. Parámetros = ' . @_ }
	}
	
	my $proc = Proc::RPC->new();
	$proc->rpc(\&return_sub, 'param1', 'param2', 'param3');
	my $r = $proc->join();
	
	is_deeply(&{$r->result()->[0]}, &{return_sub()}, "Join method returning a sub routine");
}


# Testing static join method call
##########################################################################################################
{
	sub calc_pi 
	{
	    my ($id, $N, $np) = @_;
	    my $sum = 0;
	
	    foreach (grep { $_ % $np eq $id } (0 .. $N)) {
	      my $x = ($_ + 0.5) / $N;
	      $sum += 4 / (1 + $x * $x)
	    }
	
	    return $sum / $N;
	};
	my @procs;
	my $N = 1000;
	my $np = 10;
	my $pi = 0;
	
	$procs[$_] = Proc::RPC->new() for(0..$np-1);	
	$procs[$_]->rpc( \&calc_pi, $_, $N, $np) for(0..$np-1);

	$pi += Proc::RPC->join() for (1..$np);
		
	ok($pi > 3.14 && $pi < 3.16, 'Testing static join');	
	
}
done_testing();
